package com.kuding.sms;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuding.enums.AliyunSmsApiErrorCode;
import com.kuding.exceptions.VinusException;
import com.kuding.props.AliYunSMSProperty;

public class SmsComponent {

	private final ObjectMapper objectMapper;

	private static final Log logger = LogFactory.getLog(SmsComponent.class);

	private final Config config = new Config();

	public SmsComponent(ObjectMapper objectMapper, AliYunSMSProperty aliYunSMSProperty) {
		config.accessKeyId = aliYunSMSProperty.getAccessKeyId();
		config.accessKeySecret = aliYunSMSProperty.getSecret();
		config.endpoint = aliYunSMSProperty.getEndPoint();
		config.connectTimeout = Long.valueOf(aliYunSMSProperty.getConnectionTimeout().toMillis()).intValue();
		config.readTimeout = Long.valueOf(aliYunSMSProperty.getReadTimeout().toMillis()).intValue();
		config.regionId = aliYunSMSProperty.getRegionId();
		this.objectMapper = objectMapper;

	}

	private final Client createClient() {
		try {
			return new Client(config);
		} catch (Exception e) {
			throw new VinusException("创建短信客户端错误", e);
		}
	}

	public void doSendSms(String phone, String smsSignature, String templateCode, Map<String, String> map) {
		var client = createClient();
		try {
			SendSmsRequest request = new SendSmsRequest();
			request.setSignName(smsSignature);
			request.setTemplateCode(templateCode);
			request.setTemplateParam(objectMapper.writeValueAsString(map));
			request.setPhoneNumbers(phone);
			if (logger.isDebugEnabled())
				logger.debug(String.format("准备开始发送短信：%s——%s——%s", phone, templateCode, map.toString()));
			SendSmsResponse httpResponse = client.sendSms(request);
			if (!"OK".equals(httpResponse.getBody().code)) {
				if (logger.isDebugEnabled())
					logger.debug("request exception, requestId:" + httpResponse.body.getRequestId());
				throw new VinusException(AliyunSmsApiErrorCode.getMessage(httpResponse.body.message));
			}
		} catch (Exception e) {
			throw new VinusException("短信验证码出错", e);
		}
	}
}
